package com.xiaowei.gym.gymjsp.ware.servlet;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.mysql.cj.util.StringUtils;
import com.xiaowei.gym.gymjsp.ware.entity.AdminEntity;
import com.xiaowei.gym.gymjsp.ware.entity.EquipmentEntity;
import com.xiaowei.gym.gymjsp.ware.entity.ReservationEntity;
import com.xiaowei.gym.gymjsp.ware.service.EquipmentService;
import com.xiaowei.gym.gymjsp.ware.service.impl.EquipmentServiceImpl;
import com.xiaowei.gym.gymjsp.ware.util.Constants;
import com.xiaowei.gym.gymjsp.ware.util.PageSupport;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

@WebServlet("/gymjsp/equipment.do")
public class EquipmentServlet extends HttpServlet {

    private EquipmentService equipmentService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String servletPath = req.getServletPath();
        String method = req.getParameter("method");
        if (method != null && method.equals("query")){
            this.equipmentQuery(req,resp);
        }else if (method != null && method.equals("view")){
            this.getById(req,resp,"equipment/equipmentview.jsp");
        }else if (method != null && method.equals("modify")){
            this.getById(req,resp,"equipment/equipmentmodify.jsp");
        }else if (method != null && method.equals("modifyexe")){
            this.modify(req,resp);
        }else if (method != null && method.equals("add")){
            this.add(req,resp);
        }else if (method != null && method.equals("delequipment")){
            this.delequipment(req,resp);
        }
    }

    private void delequipment(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("eid");
        System.out.println("获取到的id:"+id);
        String[] ids = JSON.parseObject(id,String[].class);
        Integer[] delId = new Integer[ids.length];
        try {
            delId = Arrays.stream(ids)
                    .mapToInt(Integer::parseInt)
                    .boxed()
                    .toArray(Integer[]::new);
            System.out.println("delId长度:"+delId.length);
            System.out.println("delId:"+delId.toString());
        } catch (Exception e) {
            // TODO: handle exception
            delId[0] = 0;
        }
        HashMap<String, String> resultMap = new HashMap<>();
        if (delId.length <= 0 ) {
            resultMap.put("delResult", "notexist");
        } else {
            if (equipmentService.delByIds(delId)) {
                resultMap.put("delResult", "true");
            } else {
                resultMap.put("delResult", "false");
            }
        }
        //把resultMap转换成json对象输出
        resp.setContentType("application/json");
        PrintWriter outPrintWriter = resp.getWriter();
        Gson gson = new Gson();
        outPrintWriter.write(gson.toJson(resultMap));
        outPrintWriter.flush();
        outPrintWriter.close();
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("equipmentname");
        String status = req.getParameter("equimentStatus");
        String description = req.getParameter("description");
        EquipmentEntity equipmentEntity = new EquipmentEntity();
        equipmentEntity.setName(name);
        equipmentEntity.setStatus(status);
        equipmentEntity.setDescription(description);
        int equipment = equipmentService.add(equipmentEntity);
        if (equipment > 0) {
            System.out.println(req.getContextPath());
            resp.sendRedirect(req.getContextPath() + "/gymjsp/equipment.do?method=query");
        } else {
            req.getRequestDispatcher("equipment/equipmentadd.jsp").forward(req, resp);
        }
    }

    private void modify(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String eid = req.getParameter("eid");
        String status = req.getParameter("equimentStatus");
        String name = req.getParameter("equipmentname");
        String description = req.getParameter("description");
        EquipmentEntity equipmentEntity = new EquipmentEntity();
        equipmentEntity.setId(Integer.valueOf(eid));
        equipmentEntity.setStatus(status);
        equipmentEntity.setName(name);
        equipmentEntity.setDescription(description);

        if (equipmentService.modify(equipmentEntity)) {
            resp.sendRedirect(req.getContextPath() + "/gymjsp/equipment.do?method=query");
        } else {
            req.getRequestDispatcher("equipment/equipmentmodify.jsp").forward(req, resp);
        }
    }

    private void getById(HttpServletRequest req, HttpServletResponse resp, String url) throws ServletException, IOException {

        String eid = req.getParameter("eid");

        if (!StringUtils.isNullOrEmpty(eid)) {
            //调用后台方法得到user对象
            EquipmentEntity equipmentEntity = equipmentService.getById(Integer.valueOf(eid));;
            req.setAttribute("equipment", equipmentEntity);
            req.getRequestDispatcher(url).forward(req, resp);
        }

    }

    private void equipmentQuery(HttpServletRequest request, HttpServletResponse resp) throws IOException, ServletException {

        //从前端获取数据
        String name = request.getParameter("name");
        String pageIndex = request.getParameter("pageIndex");
        int queryUserRole = 0;
        List<EquipmentEntity> equipmentEntityList = null;
        //第一次走这个请求，一定是第一页，页面大小是固定的
        //设置页面容量
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize") == null ? String.valueOf(Constants.pageSize) : request.getParameter("pageSize"));
        if (pageSize == null){
            pageSize = Constants.pageSize;
        }
        //默认当前页码
        int currentPageNo = 1;
        if (StringUtils.isNullOrEmpty(name)) {
            name = "";
        }

        if (pageIndex != null) {
            try {
                currentPageNo = Integer.valueOf(pageIndex);
            } catch (NumberFormatException e) {
                resp.sendRedirect("gymjsp/error.jsp");
            }
        }
        //总数量（表）
        int i = equipmentService.getCount();
        int totalCount = i;
        //总页数
        PageSupport pages = new PageSupport();
        pages.setCurrentPageNo(currentPageNo);  //当前页
        pages.setPageSize(pageSize);            //页面大小
        pages.setTotalCount(totalCount);        //总数量

        int totalPageCount = pages.getTotalPageCount();  //总页面数量

        //控制首页和尾页
        //如果页面小于第一页，就显示第一页
        if (currentPageNo < 1) {
            currentPageNo = 1;
            //如果当前页面大于最后一页，当前页等于最后一页即可
        } else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;
        }

        //获取员工信息列表展示
        equipmentEntityList = equipmentService.getEquipmentList(name, currentPageNo, pageSize);
        System.out.println(equipmentEntityList);
        request.setAttribute("equipmentList",equipmentEntityList);
        request.setAttribute("name",name);
        request.setAttribute("totalPageCount", totalPageCount);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("pageSize",pageSize);
        request.setAttribute("currentPageNo", currentPageNo);
        request.getRequestDispatcher("equipment/equipment.jsp").forward(request,resp);
    }

    @Override
    public void init() throws ServletException {
        equipmentService = new EquipmentServiceImpl();
    }
}
